package game.core
{
	import flash.events.Event;
	
	import org.bulkLoader.comply.BulkFile;
	import org.bulkLoader.comply.BulkLoader;
	import org.bulkLoader.comply.BulkLoaderDefine;
	import org.bulkLoader.events.BulkEvent;
	import org.bulkLoader.events.BulkItemLoadingEvent;
	import org.bulkLoader.handler.BulkHandler_Swf;
	import org.bulkLoader.loadinginfo.BulkItemLoadingInfo;
	import org.bulkLoader.loadinginfo.IBulkItemLoadingInfo;

	public class ResLoadHelper
	{
		public function ResLoadHelper()
		{
			if (_instance)
				throw new Error("ResLoadHelper is single class.");
		}
		
		private static var _instance:ResLoadHelper = null;
		public static function get instance():ResLoadHelper
		{
			if (!_instance)
				_instance = new ResLoadHelper();
			return _instance;
		}
		
		////////////////////////////////////////////////////////////////////////
		// 加载玩家角色
		public function loadPlayerImage(resId:int, completeFunc:Function):void
		{
			var resUrl:String = ResUrlHelper.getPlayerImageUrl(resId);
			var resKey:String = ResKeyHelper.getPlayerImageKey(resId);
			
			loadRes(resKey, resUrl, null, completeFunc);
		}
		
		
		//
		private var resKeyToResData:Object = {};
		private var resKeyToErrorFunc:Object = {};
		private var resKeyToCompleteFunc:Object = {};
		
		private function loadRes(key:String, url:String, errorFunc:Function, completeFunc:Function):void
		{
			if (resKeyToResData[key]) {
				completeFunc(resKeyToResData[key]);
				return;
			}
			
			if (!resKeyToErrorFunc[key])
				resKeyToErrorFunc[key] = new Vector.<Function>();
			resKeyToErrorFunc[key].push(errorFunc);
			
			if (!resKeyToCompleteFunc[key])
				resKeyToCompleteFunc[key] = new Vector.<Function>();
			resKeyToCompleteFunc[key].push(completeFunc);
			
			var handler:BulkHandler_Swf = new BulkHandler_Swf(
				new BulkFile(url, {key:key}), 
				new BulkItemLoadingInfo()
			);
			
			handler.addEventListener(BulkItemLoadingEvent.ITEM_COMPLETED, onLoadResComplete);
			handler.addEventListener(BulkItemLoadingEvent.ITEM_ERROR, onLoadResError);
			handler.load();
		}
		
		protected function onLoadResError(event:BulkItemLoadingEvent):void
		{
			trace(event.file.url + "load error..");
			
			var key:String = event.file.ownParameter.key;
			
			var errorFuncs:Vector.<Function> = resKeyToErrorFunc[key];
			while (errorFuncs && errorFuncs.length)
			{
				var errorFunc:Function = errorFuncs.shift();
				errorFunc();
			}
		}
		
		protected function onLoadResComplete(event:BulkItemLoadingEvent):void
		{
			var key:String = event.file.ownParameter.key;
			var data:* = event.loadingInfo.getData();
			
			var completeFuncs:Vector.<Function> = resKeyToCompleteFunc[key];
			while (completeFuncs && completeFuncs.length)
			{
				var completeFunc:Function = completeFuncs.shift();
				completeFunc(data);
			}
		}
	}
}